package cn.cyber.wxfire.controller;

import cn.cyber.wxfire.config.WXConfig;
import cn.cyber.wxfire.service.WXChartService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("WX")
public class WXController2 {
    @Resource
    private WXConfig config;


    @RequestMapping(value="/access",method= RequestMethod.GET)
    protected String check(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求到达了");
        //取出微信服务器传过来的参数
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        String token = config.getToken();
        String[] str = {token,timestamp,nonce};
        //排序
        Arrays.sort(str);
        //组成一个字符串
        String rawStr = str[0]+str[1]+str[2];

        String encodeStr = DigestUtils.sha1Hex(rawStr);
        if(encodeStr.equalsIgnoreCase(signature)){
            System.out.println("接入成功");
            return echostr;
        }else{
            System.out.println("接入失败");
            return "接入失败";
        }

    }

    @RequestMapping(value="/access",method= RequestMethod.POST)
    protected void Post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码格式,不然中文会乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //将请求中的xml参数转成map
        Map<String,String> map = WXChartService.parseRequest(req.getInputStream());
        System.out.println(map);
        //回复消息
        /*String textMsg = "<xml><ToUserName><![CDATA["+map.get("FromUserName")+"]]></ToUserName><FromUserName><![CDATA["+map.get("ToUserName")+"]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你好]]></Content></xml>";
        resp.getWriter().print(textMsg);*/
        //处理完将响应一个xml给微信
        String respXml = WXChartService.getRespose(map);
        resp.getWriter().print(respXml);
    }


}
